from django.http import HttpResponseRedirect
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
import requests
from .models import UserModel,SFUserModel,IdentityModel
from tools.myjwt import mjwt
import time
from tools.sflfactory import factory
from tools.myredis import r
import json
from tools.baiduapi import bdapi,bdface
import time
from .serial import IdentitySerializer
import os
from django.conf import settings
# Create your views here.


class DingTalkLoginView(APIView):
    def get(self, request):
        type = str(request.query_params.get('type'))
        print(type)
        f = factory.create_sflogin(type)
        url = f.geturl()

        return Response({'url': url})


class DingTalkCallbackView(APIView):
    def post(self, request):
        code = request.data['code']
        type = str(request.data['type'])
        f = factory.create_sflogin(type)
        data = f.callback(code)

        return Response(data)




class GetImageUrlView(APIView):
    def post(self,request):
        url = request.data.get('url')
        user_id = request.data.get('user_id')
        print(url)
        data = {"user_id":user_id,'url': url}
        r.list_push('baidulist', json.dumps(data))
        r.set_str(f"bdi{user_id}", json.dumps(url))
        return Response({'url': url})



class GetUserIdCardView(APIView):
    def get (self,request):
        time.sleep(1)
        id_list = []
        url_list = []
        user_list = []
        data_list = r.list_lrange("baidulist",0,1)
        if len(data_list) < 2:
            return Response({'msg':'等待中'})
        for i in data_list:
            data = json.loads(i.decode('utf-8'))
            user_id = data.get('user_id')
            url = data.get('url')
            response = bdapi.idcard(url)
            if response != False:
                res = json.loads(response)
                username =res.get('words_result').get('姓名').get('words')
                race = res.get('words_result').get('民族').get('words')
                sex = res.get('words_result').get('性别').get('words')
                if sex == "男":
                    sex = 0
                else:
                    sex = 1
                birthday = res.get('words_result').get('出生').get('words')
                identity = res.get('words_result').get('公民身份号码').get('words')
                user_dict = {
                    'username': username,
                    'race': race,
                    'sex': sex,
                    'birthday': f'{birthday[0:4]}-{birthday[4:6]}-{birthday[6:8]}',
                    'id_card': identity,
                    'user': user_id,
                }
                user_list.append(user_dict)

            else:
                id_list.append(f"bdi{user_id}")
            url_list.append(i)
        print(url_list)
        print(id_list)
        print(user_list)


        identity_serial = IdentitySerializer(data=user_list, many=True)
        if identity_serial.is_valid():
            identity_serial.save()
        else:
            return Response({'msg': 'fail'})

        pipe = r.r.pipeline()
        pipe.multi()
        for i in url_list:
            pipe.lrem('baidulist', 1, i)  # 第二个参数是删除的数量，1 表示删除第一个匹配的元素
        if len(id_list) > 0:
            pipe.delete(*id_list)
        pipe.execute()

        return Response({'url': 'ok'})




class CheckIdentityView(APIView):
    def post(self,request):
        user_id = request.data.get('user_id')
        user_data = IdentityModel.objects.filter(user=user_id).first()
        if user_data is not None:
            return Response({'msg':'已认证','code':200})
        data = r.get_str(f"bdi{user_id}")
        if data is None:
            return Response({'msg':'ok',"code":204})
        else:
            return Response({'msg':'正在验证','code':100010})




class FaceRecognitionView(APIView):
    def post(self,request):
        file_data = request.data.get('file')
        user_id = request.data.get('user_id')
        file_name = f"{user_id}.txt"

        print(file_data)
        print(type(file_data))

        save_path = os.path.join(settings.BASE_DIR, "face", file_name)
        print(save_path)
        # if not os.path.exists(save_path):
        #     os.makedirs(save_path)

        with open(save_path, 'w') as file:
            file.write(file_data)



        return Response("ok")




class BdFaceRecognitionView(APIView):

    def post(self,request):
        image2 = request.data.get('file')
        user_id = request.data.get('user_id')

        file_name = f"{user_id}.txt"

        save_path = os.path.join(settings.BASE_DIR, "face", file_name)

        with open(save_path, 'r') as file:
            image1 = file.read()


        res = bdface.main(image1,image2)

        if res:
            return Response({'msg':'ok',"code":200})

        return Response("验证失败")












